package com.jiang.operator;

import java.security.MessageDigest;
import java.util.Date;
import java.util.concurrent.TimeUnit;

public class StringUtil {
    //Applies Sha256 to a string and returns the result.
    public static String applySha256(String input){
        try {
            //MessageDigest class provides the function of message digest(签名) algorithm for application.
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            //Applies sha256 to our input,
            byte[] hash = digest.digest(input.getBytes("UTF-8"));
            //String.getBytes(String decode)方法会根据指定的decode编码返回某字符串在该编码下的byte数组表示，之后进行签名
            StringBuffer hexString = new StringBuffer(); // This will contain hash as hexidecimal
            //StringBuffer类的成员方法前面多了一个关键字：synchronized，不用多说，这个关键字是在多线程访问时起到安全保护作用的,也就是说StringBuffer是线程安全的
            for (int i = 0; i < hash.length; i++) {
                String hex = Integer.toHexString(0xff & hash[i]);
                //& 0xFF是为了保证byte类型转int后其二进制的一致，即补零扩展。那么为什么要补零扩展呢？
                // 因为我们是要把每一个byte类型的数据都转换位16进制字符串，补零扩展的话就可以忽略前24位
                //Integer.toHexString()-此方法返回的字符串表示的无符号整数参数所表示的值以十六进制（基数为16）
                if(hex.length() == 1) hexString.append('0');//长度为1，需要增加一个0
                hexString.append(hex);//拼接
            }
            return hexString.toString(); //返回拼接之后
        }
        catch(Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static String getTimeDifference(Date startDate, Date endDate){
        String result = "";
        long duration  = endDate.getTime() - startDate.getTime();
        long diffInMilli = TimeUnit.MILLISECONDS.toMillis(duration);
        long diffInSeconds = TimeUnit.MILLISECONDS.toSeconds(duration);
        long diffInMinutes = TimeUnit.MILLISECONDS.toMinutes(duration);
        long diffInHours = TimeUnit.MILLISECONDS.toHours(duration);
        long diffInDays = TimeUnit.MILLISECONDS.toDays(duration);
        if(diffInDays>0)
            result += diffInDays + ((diffInDays>1 == true) ? " Days " : " Day ");
        if(diffInHours>0)
            result += diffInHours % 24 + ((diffInHours>1 == true) ? " Hours " : " Hour ");
        if(diffInMinutes>0)
            result += diffInMinutes % 60 + ((diffInMinutes>1 == true) ? " Minutes " : " Minute ");
        if(diffInSeconds>0)
            result += diffInSeconds % 60 + ((diffInSeconds>1 == true) ? " Seconds" : " Second");
        if(diffInMilli>0 && result.isEmpty())
            result += diffInMilli + ((diffInMilli>1 == true) ? " Milli Seconds" : " Milli Second");

        return result;
    }
}
